﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DynamicApiController;
using Furion.JsonSerialization;
using Hu.Smart.Core;
using Hu.Smart.Core.BasicData;
using Hu.Smart.Core.Excel;
using Hu.Smart.Core.Messages;
using Hu.Smart.Core.Storage;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Hu.Smart.Application
{
    /// <summary>
    /// 系统服务接口
    /// </summary>
    public class SystemAppService : ExcelExporterBase, IDynamicApiController
    {
        private readonly ISystemService _systemService;
        private readonly IRepository<CompanyDivision> _companyRepository;
        private readonly IRepository<Message> _messageRepository;
        readonly ITempFileCacheManager _tempFileCacheManager;
        private readonly IConfiguration _configuration;
        public SystemAppService(ISystemService systemService,
            IRepository<CompanyDivision> personRepository,
            ITempFileCacheManager tempFileCacheManager,
            IRepository<Message> messageRepository,
            IConfiguration configuration) : base(tempFileCacheManager)
        {
            _tempFileCacheManager = tempFileCacheManager;
            _systemService = systemService;
            _companyRepository = personRepository;
            _messageRepository = messageRepository;
            _configuration = configuration;
            var redisConnstr = App.Configuration["RedisConnectionStrings:RedisCon"];
            var slavers = App.Configuration["RedisConnectionStrings:RedisSalvers"];
            Core.Redis.RedisCacheHelper.InitGuardRedis(redisConnstr, slavers.Split(',').ToList());
        }

        /// <summary>
        /// 获取系统描述
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetDescriptionAsync()
        {
            var reportListStr = await Core.Redis.RedisCacheHelper.GetCacheAsync("all_groupscore_data", async () => {
                return await _messageRepository.AsQueryable().ToPagedListAsync(1, 20);
            });
            return reportListStr; //_systemService.GetDescription();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        public async Task<PagedList<CompanyDivision>> GetPersons()
        {
           var result = await _companyRepository.AsQueryable().ToPagedListAsync(1,20);
           return result;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        public async Task<PagedList<Message>> GetMessages()
        {
            var result = await _messageRepository.AsQueryable().ToPagedListAsync(1, 20);
            return result;
        }

        /// <summary>
        /// sql 查询
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetDatas()
        {
            var result = await "select * from T_Base_CompanyDivision".SqlQueryAsync();
            var resultStr = JsonConvert.SerializeObject(result);
            return resultStr;
        }

        /// <summary>
        /// 返回dataTable
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetDataTables()
        {
            var result = await "select * from T_Base_CompanyDivision".SqlQueryAsync();
            var resultStr = JsonConvert.SerializeObject(result);
            return resultStr;
        }

        public async Task<string> SetCaches(string content)
        {
            return await _tempFileCacheManager.GetDatetimeCache(content);
        }

        public async Task<string> GetCaches(string content)
        {
            return await _tempFileCacheManager.GetStringCache(content);
        }

        [HttpPost("complaintDaily/export")]
        public async Task<FileDto> GetExcel()
        {
            var list = await _companyRepository.AsQueryable().ToListAsync();
            return CreateExcelPackage("客诉日常查询.xlsx", ep =>
            {
                var sheet = ep.Workbook.Worksheets.Add($"客诉日常查询{DateTime.Now:yyyy-MM-dd HH:mm}");
                sheet.OutLineApplyStyle = true;

                AddHeader(sheet, "序号", "最终等级", "通报类型", "客诉创建人", "地区", "项目", "分期", "组团",
                    "事件分类", "业务场景", "客诉发生时间", "续报时间", "下次回顾时间", "最新客情舆情", "客诉事件描述",
                    "原因分类", "公关危机", "可控度", "预估成本（万元）", "线上户数", "线下户数", "维权户数", "轻伤人数", "重伤人数", "死亡人数");

                List<Func<CompanyDivision, object>> complaintDailyColumnPropertyMap = new List<Func<CompanyDivision, object>>
                {
                    _ => "",
                    p => p.CompanyName,
                    p => p.Code,
                    p => p.OrgCode,
                };

                AddObjects(sheet, 2, list, complaintDailyColumnPropertyMap.ToArray());

                //加序号
                for (int i = 0; i < list.Count; i++)
                {
                    sheet.Cells[i + 2, 1].Value = i + 1;
                }
            });
        }
    }
}
